package com.tcm.user.service;

import cn.hutool.core.util.ObjectUtil;
import com.base.core.exception.ServiceException;
import com.base.core.lang.StringUtils;
import com.base.core.utils.R;
import com.base.sms.service.verification.VerificationCodeService;
import com.tcm.user.constants.enums.LoginTypeEnum;
import com.tcm.user.factory.Authenrizer;
import com.tcm.user.factory.UserFactory;
import com.tcm.user.model.query.LoginAuthQuery;
import com.tcm.user.token.AuthenticationToken;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@DubboService(version = "1.0.0")
public class SigninServiceImpl implements SigninService {

    Logger log = LoggerFactory.getLogger(SigninServiceImpl.class);

    @Autowired
    UserFactory authFactory;

    /**
     * 手机验证码服务
     */
    @Autowired
    private VerificationCodeService verificationCodeService;

    @Override
    public R login(LoginAuthQuery loginAuthQuery) {
        try {
            String type = loginAuthQuery.getLoginType().toUpperCase();
            type = LoginTypeEnum.getValue(type);
            if(StringUtils.isEmpty(type)){
                return R.fail("登录方式不正确");
            }
            Authenrizer authenrizer = authFactory.createInstance(type);
            if (ObjectUtil.isEmpty(authenrizer)){
                return R.fail("登录失败");
            }
            AuthenticationToken authenticationToken = new AuthenticationToken() {
                @Override
                public Object getPrincipal() {
                    return loginAuthQuery.getPrincipal();
                }

                @Override
                public Object getCredentials() {
                    return loginAuthQuery.getCredential();
                }

                @Override
                public String getClientType() {
                    return loginAuthQuery.getClientType();
                }
            };
            return authenrizer.doGetAuthenticationInfo(authenticationToken);
        }catch (ServiceException e){
            return R.fail(e.getResult().getCode(),e.getMessage());
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    @Override
    public R sendVerificationCode(String phone) {
        try{
            verificationCodeService.send(phone);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
        return R.success();
    }

}
